package com.example.onlineanswer.controller;

import com.example.onlineanswer.common.annotation.RequireRole;
import com.example.onlineanswer.common.exception.ApiException;
import com.example.onlineanswer.common.result.Result;
import com.example.onlineanswer.common.util.JwtUtil;
import com.example.onlineanswer.model.dto.EmailVerifyCodeDTO;
import com.example.onlineanswer.model.dto.LoginDTO;
import com.example.onlineanswer.model.dto.RegisterDTO;
import com.example.onlineanswer.model.dto.UserProfileUpdateDTO;
import com.example.onlineanswer.model.dto.UserPasswordUpdateDTO;
import com.example.onlineanswer.model.vo.UserInfoVO;
import com.example.onlineanswer.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户控制器
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody RegisterDTO registerDTO) {
        boolean result = userService.register(registerDTO);
        return Result.success(result);
    }

    /**
     * 用户登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);
        return Result.success(token);
    }

    /**
     * 获取当前用户信息
     */
    @ApiOperation("获取当前用户信息")
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo(HttpServletRequest request) {
        // 从请求头获取token
        String authHeader = request.getHeader(jwtUtil.getHeader());
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(jwtUtil.getTokenPrefix())) {
            throw new ApiException("无效的Token");
        }

        // 解析token
        String token = authHeader.substring(jwtUtil.getTokenPrefix().length() + 1);
        if (!jwtUtil.validateToken(token)) {
            throw new ApiException("Token已过期或无效");
        }

        // 获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            throw new ApiException("无效的用户信息");
        }

        // 获取用户信息
        UserInfoVO userInfo = userService.getUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 更新个人资料
     */
    @ApiOperation("更新个人资料")
    @PutMapping("/profile")
    public Result<Boolean> updateProfile(@Valid @RequestBody UserProfileUpdateDTO profileUpdateDTO, HttpServletRequest request) {
        // 从请求头获取token
        String authHeader = request.getHeader(jwtUtil.getHeader());
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(jwtUtil.getTokenPrefix())) {
            throw new ApiException("无效的Token");
        }

        // 解析token
        String token = authHeader.substring(jwtUtil.getTokenPrefix().length() + 1);
        if (!jwtUtil.validateToken(token)) {
            throw new ApiException("Token已过期或无效");
        }

        // 获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            throw new ApiException("无效的用户信息");
        }

        // 更新个人资料
        boolean result = userService.updateProfile(userId, profileUpdateDTO);
        return Result.success(result);
    }

    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PutMapping("/password")
    public Result<Boolean> updatePassword(@Valid @RequestBody UserPasswordUpdateDTO passwordUpdateDTO, HttpServletRequest request) {
        // 从请求头获取token
        String authHeader = request.getHeader(jwtUtil.getHeader());
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(jwtUtil.getTokenPrefix())) {
            throw new ApiException("无效的Token");
        }

        // 解析token
        String token = authHeader.substring(jwtUtil.getTokenPrefix().length() + 1);
        if (!jwtUtil.validateToken(token)) {
            throw new ApiException("Token已过期或无效");
        }

        // 获取用户ID
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            throw new ApiException("无效的用户信息");
        }

        // 修改密码
        boolean result = userService.updatePassword(userId, passwordUpdateDTO);
        return Result.success(result);
    }

    /**
     * 发送邮箱验证码
     */
    @ApiOperation("发送邮箱验证码")
    @PostMapping("/email/code")
    public Result<Boolean> sendEmailVerifyCode(@Valid @RequestBody EmailVerifyCodeDTO emailVerifyCodeDTO) {
        boolean result = userService.sendEmailVerifyCode(emailVerifyCodeDTO.getEmail());
        return Result.success(result);
    }

    /**
     * 检查用户名是否已存在
     */
    @ApiOperation("检查用户名是否已存在")
    @GetMapping("/check/username")
    public Result<Boolean> checkUsernameExists(@RequestParam String username) {
        boolean exists = userService.checkUsernameExists(username);
        return Result.success(exists);
    }

    /**
     * 检查邮箱是否已存在
     */
    @ApiOperation("检查邮箱是否已存在")
    @GetMapping("/check/email")
    public Result<Boolean> checkEmailExists(@RequestParam String email) {
        boolean exists = userService.checkEmailExists(email);
        return Result.success(exists);
    }
} 